<template>
  <div>
    <el-table :data="classifyList" height="500" border style="width: 96%">
      <el-table-column type="index" label="#" width="50"> </el-table-column>
      <el-table-column prop="name" label="类别名称">
        <template slot-scope="scope">
          <div v-if="scope.$index == 0">
            <el-input clearable  @keyup.enter.native="save" v-model="input" placeholder="请输入内容"></el-input>
          </div>
          <div v-else>
             <div  @dblclick="handelEditIpt(scope.row)"   v-if="editVal.id!=scope.row.id">{{ scope.row.name }}</div>
             <el-input @keyup.esc.native='handelEsc'  @blur="editFn" v-focus @keyup.enter.native="editFn" v-else v-model="editVal.name " placeholder="请输入内容"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="148">
        <template slot-scope="scope">
          <el-button v-if="scope.$index == 0" type="success" size="small" @click="save">保存</el-button>
          <div v-else>
            <el-button type="warning" size="small" @click="handelEditIpt(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="del(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {mapActions,mapState} from 'vuex'
export default {
  data() {
    return {
      input: "",
      editVal:{}
    };
  },
  directives:{
    focus:{
      inserted(el){
        el.children[0].focus()
      }
    }
  },
  methods: {
    ...mapActions("classfiy",['getClassify','saveClassify','delClassify','updateClassify']),
    // 取消
    handelEsc(){
      this.editVal={}
    },
    //回车保存
     async editFn(){
      //  console.log(this.editVal.name.trim());
       if(this.editVal.name&&this.editVal.name.trim()){
         console.log(111);
        await this.updateClassify(this.editVal)
       }else{
        await this.delClassify(this.editVal.id)
       }
      this.editVal={}
    },
    // 修改 双击
    handelEditIpt(row) {
      this.editVal={...row}
    },
    // 增加保存
    async save(){
      await this.saveClassify(this.input);
      this.input=''
    },
    // 删除
    async del(id){
      await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.delClassify(id)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
     
    },
    
  },  
  computed:{
    ...mapState("classfiy",['classifyList'])
  },
  mounted(){
    this.getClassify()
  },
};
</script>

<style scoped>
.el-table {
  margin: 20px auto;
}
</style>